package com.qf.commons.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class JSONUtil {

    /**
     * 把Java对象变成json字符串
     */
    public static String toJson(Object obj) {
        if (obj == null) {
            return "";
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            //将date类与时间戳格式之间进行转换
            mapper.getSerializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 把Java对象变成json字符串
     */
    public static <T> T toObj(String json, TypeReference<T> target) {
        if (json == null || json.length() == 0) {
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            //将date类与时间戳格式之间进行转换
            mapper.getSerializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            return mapper.readValue(json, target);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 把Java对象变成json字符串
     */
    public static <T> T toObj(String json, Class<T> clazz) {
        if (json == null || json.length() == 0) {
            return null;
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
